
import Singleton from "../core/design-pattern/Singleton";
import GameSetting from "../data/GameSetting";
import GlobalValue from "../data/GlobalValue";
import UserData from "../data/UserData";
import FrameLog from "../extensions/FrameLog";
import NetBase from "./NetBase";
const { ccclass, property } = cc._decorator;

@ccclass
export default class WxNet extends Singleton {
    private _netBase: NetBase = new NetBase()
    public async init() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) {
            return;
        }
        await this.wxLogin()
        await this.requestSetting()
        await this.userLogin()
    }
    /**
     * 微信登陆
    */
    private wxLogin() {
        return new Promise((resolve, reject) => {
            let param = Object.create({})
            param.success = (res) => {
                FrameLog.log("wxLogin success")
                GlobalValue.sessionInfo.user_code = res.code
                resolve(null)
            }
            param.fail = () => {
                FrameLog.log("wxLogin fail")
                reject(null)
            }
            wx.login(param);
        })
    }

    /**
     * 获取设置接口
     */
    private async requestSetting() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) return;
        let param = {
            url: ``,
            method: "GET",
            data: {}
        }
        try {
            let res = await this._netBase.request(param)
            GameSetting.getInstance().init(res)

        } catch (e) {
            console.error(`requestSetting异常`, e)
        }
    }

    /**
     * 玩家登陆
     */
    private async userLogin() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME)
            return;
        let data = Object.create({})
        data.code = GlobalValue.sessionInfo.user_code;
        let param = {
            isLoginURL: true,
            url: ``,
            method: "POST",
            data
        };

        try {
            let res: any = await this._netBase.request(param)
            GlobalValue.sessionInfo.openid = res.openid
            UserData.getInstance().setProperty({ id: res.id })
            this.sdkInit()
        } catch (error) {
            FrameLog.log("userLogin fail", error)
        }
    }

    private sdkInit() {

    }
}
